import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import {
  getArtistList,
  getBanners,
  getHotRecommend,
  getNewAlbum,
  getPlayListDetail
} from "@/views/discover/c-views/recommend/service/recommend";
import { IRecommendState } from "@/views/discover/c-views/recommend/store/type";

const initialState: IRecommendState = {
  banners: [],
  hotRecommend: [],
  newAlbum: [],
  rankings: [],
  settleSingers: []
};
export const fetchBannerDataAction = createAsyncThunk(
  "banners",
  async (arg, { dispatch }) => {
    const result = await getBanners();
    // dispatch(changeBannerAction(result.banners));  // 2. 另一种写法
    return result.banners;
  }
);

export const fetchHotRecommendDataAction = createAsyncThunk(
  "hotRecommend",
  async (arg, { dispatch }) => {
    const result = await getHotRecommend(8);
    // console.log(result);
    return result.result;
  }
);

export const fetchNewAlbumDataAction = createAsyncThunk(
  "newAlbum",
  async (arg, { dispatch }) => {
    const result = await getNewAlbum(10);
    // console.log(result)
    return result.albums;
  }
);

export const fetchSettleSingerDataAction = createAsyncThunk(
  "settleSinger",
  async (arg, { dispatch }) => {
    const result = await getArtistList(5);
    // console.log(result)
    return result.artists;
  }
)

// 根据接口文档获取排行榜id
const rankingIds = [19723756, 3779629, 2884035];
export const fetchRankingDataAction = createAsyncThunk(
  "rankingData",
  (_, { dispatch }) => {
    // 1. 获取榜单数据
    // 2. 将三个结果都拿到，统一放到一个数组中管理
    const promises: Promise<any>[] = [];
    for (const id of rankingIds) {
      promises.push(getPlayListDetail(id));
    }
    Promise.all(promises).then((res) => {
      const palylists = res
        .filter((item) => item.playlist)
        .map((item) => item.playlist);
      // console.log(palylists)
      dispatch(changeRankingsAction(palylists));
    });
  }
);

const recommendSlice = createSlice({
  name: "recommend",
  initialState,
  reducers: {
    changeRankingsAction(state, action) {
      state.rankings = action.payload;
    }
  },
  // 1. 写法一
  extraReducers: (builder) => {
    builder.addCase(fetchBannerDataAction.fulfilled, (state, action) => {
      state.banners = action.payload;
    });
    builder.addCase(fetchHotRecommendDataAction.fulfilled, (state, action) => {
      state.hotRecommend = action.payload;
    });
    builder.addCase(fetchNewAlbumDataAction.fulfilled, (state, action) => {
      state.newAlbum = action.payload;
    });
  }
});

// export const {changeBannerAction} = recommendSlice.actions;
export const { changeRankingsAction } = recommendSlice.actions;

export default recommendSlice.reducer;
